package net.edu_soft.ec.asset.controller;


import net.edu_soft.ec.asset.constant.CloudFileUrlConstant;
import net.edu_soft.ec.asset.pojo.CloudFile;
import net.edu_soft.ec.asset.service.CloudFileService;
import net.edu_soft.ec.common.util.FileUtils;
import net.edu_soft.ec.common.util.PuingUtil;
import net.edu_soft.ec.common.util.ResultVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  @author: PUING
 *  @Date: 2020/7/7 13:11
 *  @Description: 文件管理类
 */
@RestController
@RequestMapping("/cloudFile")
public class CloudFileController {

    @Autowired
    private CloudFileService cloudFileService;

    /***
     * 上传文件
     * @param file 文件
     * @return
     */
    @RequestMapping(value = "/upload")
    //@RequiresPermissions("cloudFile:upload")
    public ResultVo upload(@RequestParam("file") MultipartFile file){

        String fileUrl = null;
        CloudFile cloudFile = FileUtils.upload(file);
        if(cloudFile!=null){
            if(cloudFileService.save(cloudFile)==1){//保存成功
                fileUrl = CloudFileUrlConstant.SYS_URL +cloudFile.getUrl().replace("\\", "/");
            }
        }
        return ResultVo.succeed(null,fileUrl);
    }

    /***
     * 文件下载
     * @param request
     * @param response
     * @param name 文件名
     * @return
     */
    @RequestMapping(value = "/download")
    //@RequiresPermissions("cloudFile:upload")
    public void download(HttpServletRequest request, HttpServletResponse response, String name){
        PuingUtil.isEmpty("文件下载：输入的文件名为空！",name);
        CloudFile cloudFile = cloudFileService.find(name);
        if(cloudFile!=null){
            FileUtils.downloadFile(request, response, cloudFile.getUrl());
        }
    }
}
